import time
from datetime import datetime, timedelta

from flask import request, render_template, current_app, redirect, url_for, session, g, abort, jsonify

from info import db
from info.constants import ADMIN_USER_PAGE_MAX_COUNT, QINIU_DOMIN_PREFIX
from info.models import User, News, Category
from info.modules.admin import admin_blu


# 后台登录
from info.utils.common import user_login_data, file_upload
from info.utils.response_code import RET, error_map


@admin_blu.route('/login', methods=['GET', 'POST'])
def login():
    # GET 展示页面
    if request.method == 'GET':
        # 取出用户数据
        user_id = session.get("user_id")
        is_admin = session.get("is_admin")
        if user_id and is_admin:  # 管理员已登录, 直接跳转到后台首页
            return redirect(url_for("admin.index"))

        return render_template("admin/login.html")

    # POST 提交数据
    # 获取和校验参数
    username = request.form.get("username")
    password = request.form.get("password")
    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数不足")

    # 取出管理员数据
    try:
        user = User.query.filter(User.mobile==username, User.is_admin==True).first()
    except BaseException as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="数据操作错误")

    if not user:  # 是否有该管理员
        return render_template("admin/login.html", errmsg="管理员不存在")

    # 校验密码
    if not user.check_password(password):
        return render_template("admin/login.html", errmsg="账号/密码错误")

    # 存用户信息
    session["user_id"] = user.id
    session["is_admin"] = True

    # 登录成功, 重定向到后台首页
    return redirect(url_for("admin.index"))


# 退出登录
@admin_blu.route('/logout')
def logout():
    session.pop("user_id", None)
    session.pop("is_admin", None)
    return redirect(url_for("admin.login"))


# 后台首页
@admin_blu.route('/index')
@user_login_data
def index():
    return render_template("admin/index.html", user=g.user.to_dict())


# 用户统计
@admin_blu.route('/user_count')
def user_count():
    # 用户总数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except BaseException as e:
        current_app.logger.error(e)

    # 月新增人数  注册时间 >= 本月1号0点
    mon_count = 0

    # 获取当前日期的年和月
    t = time.localtime()
    # 构建目标日期字符串   2018-12-01
    mon_date_str = "%d-%02d-01" % (t.tm_year, t.tm_mon)
    # 将日期字符串 转为 日期对象
    mon_date = datetime.strptime(mon_date_str, "%Y-%m-%d")

    try:
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_date).count()
    except BaseException as e:
        current_app.logger.error(e)

    # 日新增人数  注册时间 >= 本月本日0点
    day_count = 0
    day_date_str = "%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday)
    day_date = datetime.strptime(day_date_str, "%Y-%m-%d")
    try:
        day_count = User.query.filter(User.is_admin == False, User.create_time >= day_date).count()
    except BaseException as e:
        current_app.logger.error(e)

    active_count = []  # 记录日注册人数
    active_time = []  # 记录日期字符串

    # 获取某日的注册人数  注册时间 >= 当日0点, < 次日0点
    for i in range(0, 30):

        begin_date = day_date - timedelta(days=i)  # 当天0点
        end_date = begin_date + timedelta(days=1)  # 次天0点

        try:
            one_day_count = User.query.filter(User.is_admin == False, User.create_time >= begin_date, User.create_time < end_date).count()

            active_count.append(one_day_count)

            # 将当天的日期对象 -> 日期字符串
            one_day_str = begin_date.strftime("%Y-%m-%d")
            active_time.append(one_day_str)

        except BaseException as e:
            current_app.logger.error(e)

    # 将列表倒序
    active_time.reverse()
    active_count.reverse()

    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_count": active_count,
        "active_time": active_time
    }

    return render_template("admin/user_count.html", data=data)


# 用户列表
@admin_blu.route('/user_list')
def user_list():
    # 获取和校验参数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(403)

    # 查询所有用户 根据页码
    try:
        pn = User.query.filter(User.is_admin == False).paginate(p, ADMIN_USER_PAGE_MAX_COUNT)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)

    data = {
        "user_list": [user.to_admin_dict() for user in pn.items],
        "total_page": pn.pages,
        "cur_page": pn.page
    }

    # 传入模板渲染
    return render_template("admin/user_list.html", data=data)


# 审核列表
@admin_blu.route('/news_review')
def news_review():
    # 获取和校验参数
    p = request.args.get("p", 1)
    keyword = request.args.get("keyword")
    try:
        p = int(p)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(403)

    # 判断是否进行搜索(是否传递keyword)
    filter_list = []
    if keyword:
        filter_list.append(News.title.contains(keyword))

    # 查询所有新闻 根据页码
    try:
        pn = News.query.filter(*filter_list).paginate(p, ADMIN_USER_PAGE_MAX_COUNT)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)

    data = {
        "news_list": [news.to_review_dict() for news in pn.items],
        "total_page": pn.pages,
        "cur_page": pn.page
    }

    # 传入模板渲染
    return render_template("admin/news_review.html", data=data)


# 审核详情页面
@admin_blu.route('/news_review_detail/<int:news_id>')
def news_review_detail(news_id):
    # 根据新闻id取出新闻数据
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)

    # 传入模板渲染
    return render_template("admin/news_review_detail.html", news=news.to_dict())


# 新闻审核
@admin_blu.route('/news_review_action', methods=['POST'])
def news_review_action():
    # 获取和校验参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    reason = request.json.get("reason")
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    
    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    
    if action not in ["accept", "reject"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    
    # 获取新闻数据
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
        
    # 根据action修改新闻状态
    if action == "accept":
        news.status = 0
    else:
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
        news.reason = reason
        news.status = -1
    
    # 返回json 
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 编辑列表
@admin_blu.route('/news_edit')
def news_edit():
    # 获取和校验参数
    p = request.args.get("p", 1)
    keyword = request.args.get("keyword")
    try:
        p = int(p)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(403)

    # 判断是否进行搜索(是否传递keyword)
    filter_list = []
    if keyword:
        filter_list.append(News.title.contains(keyword))

    # 查询所有新闻 根据页码
    try:
        pn = News.query.filter(*filter_list).paginate(p, ADMIN_USER_PAGE_MAX_COUNT)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)

    data = {
        "news_list": [news.to_review_dict() for news in pn.items],
        "total_page": pn.pages,
        "cur_page": pn.page
    }

    # 传入模板渲染
    return render_template("admin/news_edit.html", data=data)


# 编辑详情页面
@admin_blu.route('/news_edit_detail')
def news_edit_detail():
    # 获取和校验参数
    news_id = request.args.get("news_id")
    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 查询新闻数据
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    
    # 查询分类数据
    try:
        categories = Category.query.filter(Category.id != 1).all()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    
    # 标识新闻当前对应的分类
    category_list = []
    for category in categories:
        category_dict = category.to_dict()
        is_selected = False
        if category.id == news.category_id:  # 该分类为新闻所在的分类
            is_selected = True

        category_dict["is_selected"] = is_selected
        category_list.append(category_dict)

    # 传入模板渲染
    return render_template("admin/news_edit_detail.html", news=news.to_dict(), category_list=category_list)


# 提交编辑
@admin_blu.route('/news_edit_detail', methods=['POST'])
def news_edit_action():
    # 获取和校验参数
    news_id = request.form.get("news_id")
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    content = request.form.get("content")
    img_file = request.files.get("index_image")
    if not all([news_id, title, category_id, digest, content]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        news_id = int(news_id)
        category_id = int(category_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 查询新闻数据
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 修改新闻数据
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content
    if img_file:  # 如果修改了图片
        try:
            img_bytes = img_file.read()
            file_name = file_upload(img_bytes)
            news.index_image_url = QINIU_DOMIN_PREFIX + file_name
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg=error_map[RET.THIRDERR])

    # json返回
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 新闻分类
@admin_blu.route('/news_type', methods=['GET', "POST"])
def news_type():
    if request.method == 'GET':  # 展示页面
        try:
            categories = Category.query.filter(Category.id != 1).all()
        except BaseException as e:
            current_app.logger.error(e)
            return abort(500)

        return render_template("admin/news_type.html", categories=categories)

    # POST处理
    name = request.json.get("name")
    id = request.json.get("id")
    if not name:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 根据id判断行为 修改/新增分类
    if id:  # 修改
        try:
            id = int(id)
            category = Category.query.get(id)
            category.name = name
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
        
    else:  # 新增
        new_category = Category(name=name)
        db.session.add(new_category)
        
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])